﻿using System;
using System.Collections.Generic;

namespace ProblemsSet
{
    public class Problem_94 : BaseProblem
    {
        public override object GetResult()
        {
            const long max = 1000000000;
            
            long res = 0;

            var sqr = Math.Sqrt((max + 1)/(double)6);

            for (long b = 1; b <= sqr; b++ )
            {
                var sqr2 = Math.Sqrt((max + 1)/(double) 3 - b*b);
                for (var a = b+1; a <= sqr2; a++)
                {
                    var x = a*a + b*b;
                    var y = a*a - b*b;
                    var p = x;
                    var q = x - 2*y;
                    if (q == 1 || q == -1)
                    {
                        p = 3*x - q;
                        res += p;
                    }
                    y = 2*a*b;
                    q = x - 2*y;
                    if (q != 1 && q != -1) continue;
                    p = 3*x - q;
                    res += p;
                }
            }

            return res;
        }

        public override string Problem
        {
            get
            {
                return @"It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units.

We shall define an almost equilateral triangle to be a triangle for which two sides are equal and the third differs by no more than one unit.

Find the sum of the perimeters of all almost equilateral triangles with integral side lengths and area and whose perimeters do not exceed one billion (1,000,000,000).";
            }
        }

        public override bool IsSolved
        {
            get
            {
                return true;
            }
        }

        public override object Answer
        {
            get
            {
                return "518408346";
            }
        }

    }
}
